package cn.bjit.controller;

import cn.bjit.enums.BizCodeEnum;
import cn.bjit.enums.SenCodeEnum;
import cn.bjit.service.NotiyService;
import cn.bjit.util.CommonUtil;
import cn.bjit.util.JsonData;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码通知
 */
@Api(tags = "用户-通知模块")
@RestController
@RequestMapping("/api/user/v1")
@Slf4j
public class NotiyController {
    @Autowired
    private Producer captchaProducer;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private NotiyService notiyService;
    //图形验证码存储10分钟
    private static  final long CAPTCH_CODE_EXPIRED=1000*60*10;


    @ApiOperation("获取图形验证码")
    @GetMapping("/captch")
    public void captcha(HttpServletRequest request, HttpServletResponse response){
       String captchKey= this.getCaptchKey(request);  //获取keyuser-service:captch:EEADAESEASFADSF
       log.info("captchKey={}",captchKey);
        //1，获取图形验证码   8749
        String captText = captchaProducer.createText();
        log.info("图形验证码是={}",captText);
        BufferedImage bufferedImage = captchaProducer.createImage(captText); //将验证码添加到图形中
        //2，存到redis中
           stringRedisTemplate.opsForValue().set(captchKey,captText,CAPTCH_CODE_EXPIRED, TimeUnit.MILLISECONDS);
        //3，写到页面
        ServletOutputStream  servletOutputStream=null;
        try {
            servletOutputStream=response.getOutputStream();
            ImageIO.write(bufferedImage,"jpg",servletOutputStream);
            servletOutputStream.flush(); //刷新缓存
            servletOutputStream.close(); //关闭流对象
        } catch (IOException e) {
            log.info("图形验证码异常{}", e);
        }
    }

    /**
     * 获取key
     */
    public String  getCaptchKey(HttpServletRequest request) {
        String ipAddr = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String key = "user-service:captch:" + CommonUtil.MD5(ipAddr + userAgent);
        log.info("ip地址={}", ipAddr);
        log.info("userAgent={}", userAgent);
        log.info("key={}", key);
        return key;
    }

    /**
     * 发送邮箱验证码
     * @param to
     * @param captch
     * @return
     */
    @ApiOperation("邮箱验证码")
    @GetMapping("send_code")
    public JsonData sendTRegisterCode(@ApiParam(value = "邮件的接收者",required = true) String to,@ApiParam(value = "图形验证码",required = true) String captch,HttpServletRequest request){
        //1,获取redis中的key
        String captchKey = this.getCaptchKey(request);
        log.info("redis中存的图形验证码的key={}",captchKey);
        //2,根据key获取图形验证
        String captchCaptch = stringRedisTemplate.opsForValue().get(captchKey);
        log.info("图形验证码={}",captchCaptch);
        //3，比较你传递的captch和我获取的是否一致
        if(captch!=null&&captchCaptch!=null&&captch.equalsIgnoreCase(captchCaptch)){
              stringRedisTemplate.delete(captchKey);//删除redis中的key
            //如果一致，才能发送邮箱验证码
            JsonData jsonData = notiyService.sendCode(SenCodeEnum.USER_REGISTER, to);
            return jsonData;
        }else{
           return  JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR); //图形验证码错误
        }
    }
}
